<?php
/**
 * Handles the add post shortcode
 *
 * @author Tareq Hasan
 * @package WP User Frontend
 * @param $atts
 */
function wpuf_add_post_shorcode( $atts ) {
    extract( shortcode_atts( array('post_type' => 'post'), $atts ) );
    ob_start();
    if ( is_user_logged_in() ) {
        wpuf_add_post( $post_type );
    } else {
        printf( __( "This page is currently restricted. Please log out and in again.", 'wpuf' ), wp_loginout( get_permalink(), false ) );
    }
    $content =  ob_get_contents();
    ob_end_clean();
    return $content;
}
add_shortcode( 'wpuf_addpost', 'wpuf_add_post_shorcode' );
/**
 * Add posting main form
 *
 * @author Tareq Hasan
 * @package WP User Frontend
 *
 * @param $post_type
 */
function wpuf_add_post( $post_type ) {
    global $userdata;
    $userdata = get_userdata( $userdata->ID );
    $info = __( "Post It!", 'wpuf' );
    $can_post = 'yes';
    $info = apply_filters( 'wpuf_addpost_notice', $info );
    $can_post = apply_filters( 'wpuf_can_post', $can_post );
    if ( $can_post == 'yes' ) {
        ?>
        <div id="wpuf-post-area">
<strong>Guidelines on creating new documents:</strong><br><br>
1. Choose <b>one</b> of the categories below and any of its sub categories. <br><br>
2. Always start off writing using the <b>HTML tab</b> above the writing box. Do <b>not</b> simply copy and paste text here from another window. Often text will include embedded (invisible) codes that may adversely affect the look of your document. Best practice is to use Notepad and copy any text there. Then you can re-copy it from Notepad and paste it below. This will remove any unwanted formatting. To check the appearance of your document when finished click on the <b>Visual tab</b>. <br><br> 
            <form id="wpuf_new_post_form" name="wpuf_new_post_form" action="" enctype="multipart/form-data" method="POST">
                <?php wp_nonce_field( 'wpuf-add-post' ) ?>
                <ul class="wpuf-post-form">
                    <?php do_action( 'wpuf_add_post_form_top', $post_type ); //plugin hook  ?>
                   <?php wpuf_build_custom_field_form( 'top' ); ?>
                    <li>
                        <label for="new-post-title">
                            <?php echo get_option( 'wpuf_title_label' ); ?> <span class="required">*</span>
                        </label>
                        <input class="requiredField" type="text" name="wpuf_post_title" id="new-post-title" minlength="2">
                        <div class="clear"></div>
                        <p class="description"><?php echo stripslashes( get_option( 'wpuf_title_help' ) ); ?></p>
                    </li>
                    <?php
								 $wpuf_userrole = wpuf_role();
								 if ( get_option( 'wpuf_allow_choose_cat' ) == 'yes' ) {
						?>
                        <li>
                            <label for="new-post-cat">
                                <?php echo get_option( 'wpuf_cat_label' ); ?> <span class="required">*</span>
                            </label>
                            <div style="float:left; min-width: 300px;">
                                <div id="catlvl0">
											<?php 
												$exclude = get_option( 'wpuf_exclude_cat' );

												if ( $wpuf_userrole == 'member' ) $exclude .= ',7,42';

												$args=array('hierarchical' => 0, 'hide_empty' => 0, 'orderby' => 'name', 'exclude' => $exclude.',6,108');
												foreach ( get_categories($args) as $category ) {
													if ( $category->category_parent == 0 ) {
														switch ( $category->cat_ID ) {
															case 7:
																echo $category->cat_name; ?><input type="radio" class="cat requiredField" name="category[]" value="<?php echo $category->cat_ID; ?>" /><br /><?php
																wp_dropdown_categories('show_option_none=-- Select --&hierarchical=1&hide_empty=0&orderby=name&name=category[]&show_count=0&title_li=&use_desc_for_title=1&class=cat incat'.$category->cat_ID.'&depth=1&child_of='.$category->cat_ID.'&exclude='.$exclude);
																echo '<br />';
																wp_dropdown_categories('show_option_none=-- Select --&hierarchical=1&hide_empty=0&orderby=name&name=category[]&show_count=0&title_li=&use_desc_for_title=1&class=cat incat'.$category->cat_ID.'&depth=1&child_of='.$category->cat_ID.'&exclude='.$exclude);
																echo '<br />';
																wp_dropdown_categories('show_option_none=-- Select --&hierarchical=1&hide_empty=0&orderby=name&name=category[]&show_count=0&title_li=&use_desc_for_title=1&class=cat incat'.$category->cat_ID.'&depth=1&child_of='.$category->cat_ID.'&exclude='.$exclude);
																echo '<br />';
																break;
															case 37:
															case 39:
																echo $category->cat_name; ?><input type="radio" class="cat requiredField" name="category[]" value="<?php echo $category->cat_ID; ?>" /><br /><?php
																wp_dropdown_categories('show_option_none=-- Select --&hierarchical=1&hide_empty=0&orderby=name&name=category[]&show_count=0&title_li=&use_desc_for_title=1&class=cat incat'.$category->cat_ID.'&depth=1&child_of='.$category->cat_ID.'&exclude='.$exclude);
																echo '<br />';
																break;
															default:
																echo $category->cat_name; ?><input type="radio" class="cat requiredField" name="category[]" value="<?php echo $category->cat_ID; ?>" /><br />
											<?php
																break;
														}
													}
												}
											?>
                                </div>
                            </div>
                            <div class="clear"></div>
                            <p class="description"><?php echo stripslashes( get_option( 'wpuf_cat_help' ) ); ?></p>
                        </li>
                    <?php }
								  if ( $wpuf_userrole == 'member' || $wpuf_userrole == 'author' ) {
							?>
                    <li id="book_url" style="display:none;">
								<div align="left">
								<label>Enter your book's URL (include 'http://www.'):</label><div class="clear"></div>
                        Kindle<br /><input type="text" name="amazon_kindle" value="" /><br />
                        iBookstore<br /><input type="text" name="ibookstore" value="" /><br />
                        Nook<br /><input type="text" name="nook" value="" /><br />
                        Waterstones<br /><input type="text" name="waterstones" value="" /><br />
                        Referral or discount reseller<br /><input type="text" name="partner" value="" /><br />
			</div>
                        <div class="clear"></div>
                    </li>
							<?php
								}

								  if ( $wpuf_userrole != 'member' ) {
							?>
                    
                    					<?php
								}
							?>
                    <li>
                        <input type="checkbox" name="wpcr_enable" value="1" /><label>Enable reader reviews</label>
                        <div class="clear"></div>
                    </li>
							<?php
								include_once(ABSPATH.'wp-admin/includes/plugin.php');
								if ( is_plugin_active('mingle-forum/wpf-main.php') ) {
									include_once(ABSPATH.'wp-content/plugins/mingle-forum/wpf.class2.php');
									$mf = new mingleforum();
									$mf->init();
							?>
                    <li>
							
                        <div class="clear"></div>
                    </li>
							<?php
								}
							?>

                    <?php do_action( 'wpuf_add_post_form_description', $post_type ); ?>
                    <?php wpuf_build_custom_field_form( 'description' ); ?>

                    <li>
                        <label for="new-post-desc">
                            <?php echo get_option( 'wpuf_desc_label' ); ?> <span class="required">*</span>
                        </label><br><br>
<?php if(in_array('Author' ,dk_get_e_member_arr()) || in_array('Author' ,dk_get_e_member_arr())):?>        
If you wish to add an author photo or book cover use <b>Upload/Insert</b> below.<br><br>
For the best results author photos should be 200x298px and for book covers 200x300px. You can edit your image where indicated. Once you have uploaded your image to the system please contact us at authors@wonderbookland.com so we can enable the image.<br><br> 
<?php endif;?>


                        <div style="float:left;">
                            <?php if ( get_option( 'wpuf_editor_type' ) == 'rich' ) { ?>
                                <?php wp_editor( '', 'new-post-desc', array('textarea_name' => 'wpuf_post_content', 'teeny' => true, 'textarea_rows' => 20) ); ?>
                            <?php } else { ?>
                                <textarea name="wpuf_post_content" id="new-post-desc" cols="80" rows="20"></textarea>
                            <?php } ?>
                        </div>
                        <div class="clear"></div>
                        <p class="description"><?php echo stripslashes( get_option( 'wpuf_desc_help' ) ); ?></p>
                    </li>

                    <?php do_action( 'wpuf_add_post_form_after_description', $post_type ); ?>
                    <?php wpuf_build_custom_field_form( 'tag' ); ?>

                    <?php if ( get_option( 'wpuf_allow_tags' ) == 'yes' ) { ?>
                        <li>
                            <label for="new-post-tags">
                                <?php echo get_option( 'wpuf_tag_label' ); ?>
                            </label>
                            <input type="text" name="wpuf_post_tags" id="new-post-tags" class="new-post-tags">
                            <p class="description"><?php echo stripslashes( get_option( 'wpuf_tag_help' ) ); ?></p>
                            <div class="clear"></div>
                        </li>
                    <?php } ?>

                    <?php do_action( 'wpuf_add_post_form_tags', $post_type ); ?>

                    <?php wpuf_attachment_fields(); ?>

                    <?php wpuf_build_custom_field_form( 'bottom' ); ?>

                    <li style="text-align:left;">
                        <input class="wpuf_submit" type="submit" name="wpuf_new_post_submit" value="<?php echo stripslashes( get_option( 'wpuf_post_submit_label' ) ); ?>">
                        <input type="hidden" name="wpuf_post_type" value="<?php echo $post_type; ?>" />
                        <input type="hidden" name="wpuf_post_new_submit" value="yes" />
                    </li>
                    <?php do_action( 'wpuf_add_post_form_bottom', $post_type ); ?>
                </ul>
            </form>
        </div>
<script type="text/javascript">
jQuery(document).ready(function($){
	$('select[name^=category]').attr('disabled', 'disabled').val(-1);

	$('input:radio[name^=category]').live('change', function() {
		var val = $(this).val();

		$('select[name^=category]').attr('disabled', 'disabled').val(-1);

		if ( val == 7 ) {
			$('#book_url').css('display', '');
		} else {
			$('#book_url').css('display', 'none');
		}

		$('select.incat'+val).removeAttr('disabled');
	});
});
</script>
        <?php
    } else {
        echo '<div class="info">' . $info . '</div>';
    }
}
function wpuf_init_posting_check() {
    if ( has_shortcode( 'wpuf_addpost' ) ) {
        if ( isset( $_POST['wpuf_post_new_submit'] ) ) {
            $nonce = $_REQUEST['_wpnonce'];
            if ( !wp_verify_nonce( $nonce, 'wpuf-add-post' ) ) {
                wp_die( __( 'Cheating?' ) );
            }

            wpuf_validate_post_submit();
        }
    }
}
add_action( 'template_redirect', 'wpuf_init_posting_check' );
/**
 * Validate the post submit data
 *
 * @author Tareq Hasan
 * @package WP User Frontend
 *
 * @global type $userdata
 * @param type $post_type
 */
function wpuf_validate_post_submit() {
    global $userdata;
    $errors = array();
    //if there is some attachement, validate them
    if ( !empty( $_FILES['wpuf_post_attachments'] ) ) {
        $errors = wpuf_check_upload();
    }
    $title = trim( $_POST['wpuf_post_title'] );
    $content = trim( $_POST['wpuf_post_content'] );
    $tags = wpuf_clean_tags( $_POST['wpuf_post_tags'] );
    $cat = $_POST['category'];

    //validate title
    if ( empty( $title ) ) {
        $errors[] = __( 'Empty post title', 'wpuf' );
    } else {
        $title = trim( strip_tags( $title ) );
    }

    //validate cat
    if ( !is_array($cat) || count($cat) == 0 ) {
        $errors[] = __( 'Please choose a category', 'wpuf' );
    }

    //validate post content
    if ( empty( $content ) ) {
        $errors[] = __( 'Empty post content', 'wpuf' );
    } else {
        $content = trim( $content );
    }
    //process tags
    if ( !empty( $tags ) ) {
        $tags = explode( ',', $tags );
    }
    //post type
    $post_type = trim( strip_tags( $_POST['wpuf_post_type'] ) );
    //process the custom fields
    $custom_fields = array();
    $fields = wpuf_get_custom_fields();
    if ( is_array( $fields ) ) {
        foreach ($fields as $cf) {
            if ( array_key_exists( $cf['field'], $_POST ) ) {

                $temp = trim( strip_tags( $_POST[$cf['field']] ) );
                //var_dump($temp, $cf);

                if ( ( $cf['type'] == 'yes' ) && !$temp ) {
                    $errors[] = __( "{$cf['label']} is missing", 'wpuf' );
                } else {
                    $custom_fields[$cf['field']] = $temp;
                }
            } //array_key_exists
        } //foreach
    } //is_array
    $errors = apply_filters( 'wpuf_add_post_validation', $errors );
    //if not any errors, proceed
    if ( !$errors ) {
        $post_stat = ( get_option( 'wpuf_post_status' ) ) ? get_option( 'wpuf_post_status' ) : 'publish';
        $post_author = ( get_option( 'wpuf_post_author' ) == 'original' ) ? $userdata->ID : get_option( 'wpuf_map_author' );

        //users are allowed to choose category
        if ( get_option( 'wpuf_allow_choose_cat' ) == 'yes' ) {
            $post_category = $cat;
        } else {
            $post_category = array(get_option( 'wpuf_default_cat' ));
        }

        $my_post = array(
            'post_title' => $title,
            'post_content' => $content,
            'post_status' => $post_stat,
            'post_author' => $post_author,
            'post_category' => $post_category,
            'post_type' => $post_type,
            'tags_input' => $tags
        );

        //plugin API to extend the functionality
        $my_post = apply_filters( 'wpuf_add_post_args', $my_post );

        //insert the post
        $post_id = wp_insert_post( $my_post );

        if ( $post_id ) {

            //upload attachment to the post
            wpuf_upload_attachment( $post_id );

            //send mail notification
            if ( get_option( 'wpuf_notify' ) == 'yes' ) {
                wpuf_notify_post_mail( $userdata, $post_id );
            }

            //add the custom fields
            if ( $custom_fields ) {
                foreach ($custom_fields as $key => $val) {
                    add_post_meta( $post_id, $key, $val, true );
                }
            }

				update_post_meta($post_id, 'wpcr_enable', (int) isset($_POST['wpcr_enable']));

				if ( $wpuf_userrole != 'member' ) {
					update_post_meta($post_id, 'synch_featured', 'off');
					update_post_meta($post_id, 'synch_slider', ( ( (int) isset($_POST['synch_slider']) ) ? 'on' : 'off' ));
				}

				if ( in_array(7, $cat) ) {
					update_post_meta($post_id, 'amazon_kindle', $_POST['amazon_kindle']);
					update_post_meta($post_id, 'ibookstore', $_POST['ibookstore']);
					update_post_meta($post_id, 'nook', $_POST['nook']);
					update_post_meta($post_id, 'waterstones', $_POST['waterstones']);
					update_post_meta($post_id, 'partner', $_POST['partner']);
				}
				
            //plugin API to extend the functionality
            do_action( 'wpuf_add_post_after_insert', $post_id );

				include_once(ABSPATH.'wp-admin/includes/plugin.php');
				if ( is_plugin_active('mingle-forum/wpf-main.php') && $_POST['mf_post_to_forum_forum'] > 0 ) {
					include_once(ABSPATH.'wp-content/plugins/mingle-forum/wpf.class2.php');
					$mf = new mingleforum();
					$mf->init();

					global $wpdb, $user_ID;

					$date = $mf->wpf_current_time_fixed('mysql', 0);
					$fid = $_POST['mf_post_to_forum_forum'];
					$post = get_post($post_id);

					$sql_thread = "INSERT INTO {$mf->t_threads} (last_post, subject, parent_id, `date`, status, starter) VALUES('{$date}', '".$mf->strip_single_quote($title)."', '{$fid}', '{$date}', 'open', '{$user_ID}')";
					$wpdb->query($sql_thread);
					$tid = $wpdb->insert_id;
					$sql_post = "INSERT INTO {$mf->t_posts} (text, parent_id, `date`, author_id, subject) VALUES('".$mf->input_filter($wpdb->escape($content))."', '{$tid}', '{$date}', '{$user_ID}', '".$mf->strip_single_quote($title)."')";
					$wpdb->query($wpdb->prepare($sql_post));

		        $my_post = array(
					  'ID' => $post_id,
      		     'post_title' => $title,
		           'post_content' => $content."\n".'<p><a href="'.$mf->get_threadlink($tid).'">'.__("Join the Forum discussion on this post", "mingleforum").'</a></p>',
                 'post_status' => $post_stat,
                 'post_author' => $post_author,
                 'post_category' => $post_category,
                 'post_type' => $post_type,
                 'tags_input' => $tags
        		  );
				  wp_update_post($my_post);
				}

            //echo '<div class="success">' . __('Document published successfully', 'wpuf') . '</div>';
            if ( $post_id ) {
                $redirect = get_permalink($post_id);
                $redirect = apply_filters('wpuf_after_post_redirect', $redirect, $post_id);
                wp_redirect( $redirect );
            }
        }
    } else {
        echo wpuf_error_msg( $errors );
    }
}